<?php
namespace app\common\utils;

/**
 * openssl 对称加解密
 */
class Crypter
{

    /**
     * @var string
     */
    protected $key;

    /**
     * @var string
     */
    protected $cipher;

    /**
     * @param string $key
     * @param string $cipher
     */
    public function __construct($key, $cipher = 'AES-256-CBC')
    {
        $this->key    = $key;
        $this->cipher = $cipher;
    }

    /**
     * 加密
     *
     * @param string $value
     * @return string
     */
    public function encrypt($value)
    {
        if (empty($value)) {
            return "";
        }

        try {
            $iv    = random_bytes(openssl_cipher_iv_length($this->cipher));
            $value = openssl_encrypt($value, $this->cipher, $this->key, 0, $iv);

            if ($value === false) {
                return false;
            }

            $iv = base64_encode($iv);

            return base64_encode(json_encode(compact('iv', 'value')));
        } catch (\Exception $e) {
            return false;
        }
    }

    /**
     * 解密
     *
     * @param string $payload
     * @return string
     */
    public function decrypt($payload)
    {
        if (empty($payload)) {
            return "";
        }

        try {
            $payload   = json_decode(base64_decode($payload), true);
            $iv        = base64_decode($payload['iv']);
            $decrypted = openssl_decrypt($payload['value'], $this->cipher, $this->key, 0, $iv);

            if ($decrypted === false) {
                return false;
            }

            return $decrypted;
        } catch (\Exception $e) {
            return false;
        }
    }
}
